<template>
  <div class="login-container">
    <el-card class="login-card" shadow="always">
      <template #header>
        <div class="login-header">
          <h1>CRM旅游管理系统</h1>
          <p>专为中老年旅游客户设计的智能化管理平台</p>
        </div>
      </template>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        size="large"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            clearable
            autocomplete="username"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
            autocomplete="current-password"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <div class="form-options">
            <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
            <el-button type="text" @click="handleForgotPassword">忘记密码？</el-button>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>还没有账户？<el-button type="text" @click="handleRegister">立即注册</el-button></p>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useSystemStore } from '@/stores/system'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import logger from '@/utils/logger'

const router = useRouter()
const systemStore = useSystemStore()
const userStore = useUserStore()

const loginFormRef = ref()
const loading = ref(false)

// 表单数据
const loginForm = ref({
  username: 'admin',
  password: '123456',
  remember: false
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ]
}

// 登录处理
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    // 模拟登录请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 设置用户信息
    userStore.setUserInfo({
      id: '1',
      username: loginForm.value.username,
      nickname: '管理员',
      avatar: '',
      email: 'admin@example.com',
      phone: '138****8888',
      department: '技术部',
      role: '系统管理员',
      permissions: ['*'],
      lastLoginTime: new Date().toISOString()
    })
    
    userStore.setAuthenticated(true)
    
    if (loginForm.value.remember) {
      // 保存登录状态
      localStorage.setItem('remember-login', 'true')
    }
    
    ElMessage.success('登录成功')
    
    // 跳转到首页
    router.push('/dashboard')
    
    logger.info('用户登录成功', { username: loginForm.value.username })
    
  } catch (error) {
    console.error('登录失败:', error)
    if (error !== false) { // 表单验证失败时error为false
      ElMessage.error('登录失败，请检查用户名和密码')
    }
  } finally {
    loading.value = false
  }
}

// 忘记密码
const handleForgotPassword = () => {
  router.push('/forgot-password')
}

// 注册
const handleRegister = () => {
  router.push('/register')
}

onMounted(() => {
  // 检查是否有记住的登录状态
  const rememberLogin = localStorage.getItem('remember-login')
  if (rememberLogin) {
    loginForm.value.remember = true
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
}

.login-header h1 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.login-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.login-form {
  margin-top: 20px;
}

.form-options {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.login-button {
  width: 100%;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}

.login-footer p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}
</style>